package com.portal.framework.common;

import java.util.List;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class PaginationHQL {
	private int currentPage = 1; // 单前页
	private int totalRows; // 总记录数
	
	private int totalPage; // 总页数
	private int rowIndex;// 当前页起始序号
	private int firstRow; // 起始记录
	
	private int pageSize = 20; // 每页记录数
	private String parameterStr; // 其它条件
	
	private String orderStr;// 排序条件
	
	private String hql; // sql查询语句
	
	private HibernateTemplate hibernateTemplate;//
	
	private List resultList; // 结果集
	private String whereStr = "";
	
	private Class dtoClass;// dto类对象
	private String singleHQL;
	
	public PaginationHQL() {
	}

	public List getResultList() {
		return resultList;
	}

	public void setResultList(List resultList) {
		this.resultList = resultList;
	}

	public PaginationHQL(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public PaginationHQL(HibernateTemplate hibernateTemplate, int pageSize) {
		this.hibernateTemplate = hibernateTemplate;
		this.pageSize = pageSize;
	}

	/**
	 * 获得每页要显示的结果集
	 * @param firstRow
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	private List find(int firstRow, int pageSize) throws Exception {
		Query query = this.hibernateTemplate.getSessionFactory().openSession()
				.createQuery(replaceHqlStr(hql));
		query.setFirstResult(firstRow);
		query.setMaxResults(pageSize);
		List list = query.list();
		return list;
	}

	/**
	 * 替换字符串
	 * @param str
	 * @return
	 */
	private String replaceHqlStr(String str) {
		str = str.replace('^', '\'').replace('~', ' ').replace('{', '=')
				.replace('}', '%');
		return str;
	}

	/**
	 * 获得所有结果集,用于报表
	 * @param hsql
	 * @param firstRow
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	public List findAll() throws Exception {
		Query qr = this.hibernateTemplate.getSessionFactory().openSession()
				.createQuery(replaceHqlStr(hql));
		return qr.list();
	}

	/**
	 * 获得总行数
	 * @return
	 */
	private int findTotleRows() {
		String coutHql = "";
		if (this.singleHQL != null && !this.singleHQL.trim().equals("")) {
			int index = this.singleHQL.indexOf("from");
			int eindex = this.singleHQL.indexOf("order by");
			int eindexH = this.singleHQL.indexOf("ORDER BY");
			if(eindex==-1) eindex = this.singleHQL.length();
			if(eindexH!=-1) eindex = eindexH;
			coutHql = this.singleHQL.substring(index,eindex);
			coutHql = "select count(*) " + coutHql;
		} else {
			int eindex = this.hql.indexOf("order by");
			int eindexH = this.hql.indexOf("ORDER BY");
			if(eindex==-1) eindex = this.hql.length();
			if(eindexH!=-1) eindex = eindexH;
			coutHql = "select count(*) " + this.hql.substring(0, eindex);
		}
		totalRows = ((Long) getHibernateTemplate().iterate(coutHql).next())
				.intValue();
		return totalRows;
	}

	public List getResult() throws Exception {
		this.setHql();
		totalRows = this.findTotleRows();// 计算总记录数
		this.totalPage = (this.totalRows + pageSize - 1) / pageSize;// 计算总页数
		if (this.totalPage <= 0) {
			// 总页数<=0当前页数为1
			this.currentPage = 1;
			this.firstRow = 0;//
		} else if (currentPage > this.totalPage) {
			this.currentPage = this.totalPage;
			this.firstRow = (this.currentPage - 1) * pageSize;
		} else {
			this.firstRow = (currentPage - 1) * pageSize;
		}
		if (firstRow <= 0) {
			firstRow = 0;
		}
		if (currentPage <= 0) {
			currentPage = 1;
		}
		this.resultList = this.find(firstRow, this.getPageSize());
		return resultList;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getFirstRow() {
		return firstRow;
	}

	public void setFirstRow(int firstRow) {
		this.firstRow = firstRow;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getParameterStr() {
		return parameterStr;
	}

	public void setParameterStr(String parameterStr) {
		this.parameterStr = parameterStr;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getTotalRows() {
		return totalRows;
	}

	public void setTotalRows(int totalRows) {
		this.totalRows = totalRows;
	}

	public String getWhereStr() {
		return whereStr;
	}

	public void setWhereStr(String whereStr) {
		this.whereStr = whereStr;
	}

	public void setHql() {
		if (singleHQL == null || singleHQL.trim().equals("")) {
			StringBuffer s = new StringBuffer("FROM ");
			s.append(this.getDtoClass().getName());
			if (whereStr != null && !whereStr.trim().equals("")) {
				s.append(" " + this.replaceHqlStr(whereStr));
				if (this.parameterStr != null
						&& !this.parameterStr.trim().equals("")) {
					s.append(" AND " + parameterStr);
				}
			} else {
				if (this.parameterStr != null
						&& !this.parameterStr.trim().equals("")) {
					s.append(" WHERE " + this.parameterStr);
				}
			}
			if (this.orderStr != null && !this.orderStr.trim().equals("")) {
				s.append(" " + this.orderStr);
			}
			this.hql = s.toString();
		} else {
			this.hql = this.singleHQL;
		}
	}

	public int getRowIndex() {
		rowIndex = this.getFirstRow() + 1;
		return rowIndex;
	}

	public void setRowIndex(int rowIndex) {
		this.rowIndex = rowIndex;
	}

	public Class getDtoClass() {
		return dtoClass;
	}

	public void setDtoClass(Class dtoClass) {
		this.dtoClass = dtoClass;
	}

	public void setOrderStr(String orderStr) {
		this.orderStr = orderStr;
	}

	public String getSingleHQL() {
		return singleHQL;
	}

	public void setSingleHQL(String singleHQL) {
		this.singleHQL = singleHQL;
	}
}